﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Crank.Core
{
    class AliasTransformer : IModelTransformer
    {
        #region Blackboard Variables

        // Alias, Real
        private static readonly IProperty<IDictionary<string, string>> EntityAliases = Blackboard.Create<IDictionary<string, string>>("EntityAliases");

        #endregion

        private IDictionary<string, string> Aliases
        {
            get
            {
                return EntityAliases.Value;
            }
        }


        #region IModelTransformer Members

        public void ApplyTransform(DataModel target)
        {
            var killList = new List<string>();
            var entityNames = target.Entities.Keys.ToArray();
            foreach (var alias in Aliases.Keys)
            {
                foreach (var entityName in entityNames)
                {
                    if (String.Compare(alias, entityName, true) == 0)
                    {
                        var copy = target.GetEntityByName(alias);
                        var real = target.GetEntityByName(Aliases[alias]);
                        CopyAttributes(copy, real);
                        ShiftLinks(copy, real, target.Links);
                        killList.Add(alias);
                    }
                }
            }
            foreach (var entityName in killList)
                target.Entities.Remove(entityName);
        }

        private void CopyAttributes(EntityDef copy, EntityDef real)
        {
            foreach (var att in copy.Attributes)
                real.Attributes.Add(new AttributeDef(att));
        }

        private void ShiftLinks(EntityDef copy, EntityDef real, IList<LinkDef> links)
        {
            foreach (var link in links)
            {
                if (link.LHS == copy)
                    link.LHS = real;
                if (link.RHS == copy)
                    link.RHS = real;
            }
        }

        #endregion
    }
}
